package com.neusoft.elm_servlet.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.neusoft.elm_servlet.dao.UserDao;
import com.neusoft.elm_servlet.po.User;
import com.neusoft.elm_servlet.util.DBUtil;

public class UserDaoImpl implements UserDao{

	@Override
	public User getUserByIdByPass(String userId, String password) throws SQLException {
		Connection con = DBUtil.getConnection();
		PreparedStatement ps = con.prepareStatement("SELECT * FROM user WHERE userId = ? and password=?");
		ps.setString(1, userId);
		ps.setString(2, password);
		ResultSet rs = ps.executeQuery();
		User user = null;
		while(rs.next()){
			user = new User();
			user.setUserId(userId);
			user.setUserName(rs.getString("userName"));
			user.setUserSex(rs.getInt("userSex"));
		}
		DBUtil.close(rs, ps, con);
		return user;
	}

	@Override
	public int saveUser(User user) throws SQLException {
		Connection con = DBUtil.getConnection();
		PreparedStatement ps = con.prepareStatement("insert into "
				+ " user values(?,?,?,?,'',1)");
		ps.setString(1,user.getUserId());
		ps.setString(2, user.getPassword());
		ps.setString(3, user.getUserName());
		ps.setInt(4, user.getUserSex());
		int count = ps.executeUpdate();
		DBUtil.close(null, ps, con);
		return count;
	}

	@Override
	public int getUserById(String userId) throws SQLException {
		Connection con = DBUtil.getConnection();
		PreparedStatement ps = con.prepareStatement("SELECT count(*) FROM user WHERE userId = ? ");
		ps.setString(1, userId);
		ResultSet rs = ps.executeQuery();
		int count = 0;
		while(rs.next()){
			count = rs.getInt(1);
		}
		DBUtil.close(rs, ps, con);
		return count;
	}

}
